<template>
    <view>
        <!-- 骨架屏 -->
        <tui-skeleton v-if="skeletonShow" :isLoading="false" backgroundColor="#fafafa" borderRadius="10rpx"></tui-skeleton>
        <view class="container tui-skeleton">
            <!--header-->
            <view class="tui-header">
				<view class="tui-placeholder" :style="{height: `${statusBar.top}px`}"></view>
				<view class="tui-header-container" :style="{height: `${statusBar.height}px`}">
					<view class="tui-category tui-skeleton-fillet" hover-class="opcity" :hover-stay-time="150" @tap="HANDLE_JUMP_CATE">
					    <tui-icon name="manage-fill" color="#fff" :size="22"></tui-icon>
					    <!-- <view class="tui-category-scale">分类</view> -->
					</view>
					<view class="tui-rolling-search tui-skeleton-fillet" :style="{marginRight: `${statusBar.menuWidth}px`}">
					    <icon type="search" :size="14" color="#999"></icon>
					    <swiper vertical autoplay circular interval="8000" class="tui-swiper">
					        <swiper-item v-for="(item, index) in PL_TOP_3_CATES" :key="index" class="tui-swiper-item" @tap="search">
					            <view class="tui-hot-item">{{ item }}</view>
					        </swiper-item>
					    </swiper>
					</view>
				</view>
            </view>
            <!--banner-->
            <view class="tui-header-banner" :style="{paddingTop: `${statusBar.top + statusBar.height + (mallOwner ? 35 : 0)}px`}">
                <view class="tui-banner-bg">
                    <view class="tui-primary-bg tui-route-left"></view>
                    <view class="tui-primary-bg tui-route-right"></view>
                    <!--banner-->
                    <view class="tui-banner-box tui-skeleton-rect">
						<view class="mall-owner" v-if="mallOwner">
							<view class="owner-wrapper">
								<view class="owner-avatar">
									<image class="owner-avatar-img" :src="mallOwner.avatarUrl" mode="aspectFill"></image>
								</view>
								欢迎来到{{mallOwner.nickName}}的商城
							</view>
						</view>
                        <swiper
                            :indicator-dots="true"
                            :autoplay="true"
                            :interval="5000"
                            :duration="150"
                            class="tui-banner-swiper"
                            :circular="true"
                            indicator-color="rgba(255, 255, 255, 0.8)"
                            indicator-active-color="#fff">
                            <swiper-item v-for="(item, index) in banner" @click="handleBannerClick(item)" :key="index">
                                <image :src="item.bannerPic" class="tui-slide-image" mode="scaleToFill" />
                            </swiper-item>
                        </swiper>
                    </view>
                </view>
            </view>
			
			<view class="tui-proxy-info">
				
			</view>
			
			<!--类目-->
			<view class="tui-product-category tui-skeleton-fillet">
				<swiper
					:indicator-dots="true"
					class="tui-catetory-swiper"
					indicator-active-color="#e41f19">
					<swiper-item v-for="(group, $index) in category" :key="$index">
						<view class="tui-catetory-group">
							<view class="tui-category-item"
								v-for="(item, index) in group" :key="index" 
								@tap="HANDLE_JUMP_CATE({currentTab: index})"
								:data-key="item.name">
							    <image :src="item.categoryPic" class="tui-category-img tui-skeleton-circular" mode="aspectFill"></image>
							    <view class="tui-category-name">{{ item.categoryName }}</view>
							</view>
						</view>
					</swiper-item>
				</swiper>
			</view>

            <view class="tui-product-box ">
                <view class="tui-group-name"><text class="tui-skeleton-fillet">热门推荐</text></view>
                <view v-if="PRODUCTS_LIST.length!=0" class="tui-product-list">
                    <view class="tui-product-container">
                        <block v-for="(item, index) in PRODUCTS_LIST" :key="index" v-if="(index + 1) % 2 != 0">
                            <!--商品列表-->
                            <view class="tui-pro-item" hover-class="hover" :hover-start-time="150" @tap="GOODS_DETAIL(item)">
                                <image :src="item.pic" class="tui-pro-img tui-skeleton-rect" mode="widthFix" />
                                <view class="tui-pro-content">
                                    <view class="tui-pro-tit tui-skeleton-rect">{{ item.productName }}</view>
                                    <view>
                                        <view class="tui-pro-price">
                                            <text class="tui-sale-price tui-skeleton-rect">￥{{ item.soldPrice || 0 }}</text>
                                            <text class="tui-factory-price tui-skeleton-rect" v-if="item.price">￥{{ item.price }}</text>
                                        </view>
                                        <view class="tui-pro-pay tui-skeleton-rect">{{ item.soldStock }}人付款</view>
                                    </view>
                                </view>
                            </view>
                            <!--商品列表-->
                            <!-- <template is="productItem" data="{{item,index:index}}" /> -->
                        </block>
                    </view>
                    <view class="tui-product-container">
                        <block v-for="(item, index) in PRODUCTS_LIST" :key="index" v-if="(index + 1) % 2 == 0">
                            <!--商品列表-->
                            <view class="tui-pro-item" hover-class="hover" :hover-start-time="150" @tap="GOODS_DETAIL(item)">
                                <image :src="item.pic" class="tui-pro-img tui-skeleton-rect" mode="widthFix" />
                                <view class="tui-pro-content">
                                    <view class="tui-pro-tit tui-skeleton-rect">{{ item.productName }}</view>
                                    <view>
                                        <view class="tui-pro-price">
                                            <text class="tui-sale-price tui-skeleton-rect">￥{{ item.soldPrice || 0 }}</text>
                                            <text class="tui-factory-price tui-skeleton-rect" v-if="item.price">￥{{ item.price }}</text>
                                        </view>
                                        <view class="tui-pro-pay tui-skeleton-rect">{{ item.soldStock }}人付款</view>
                                    </view>
                                </view>
                            </view>
                            <!--商品列表-->
                            <!-- <template is="productItem" data="{{item,index:index}}" /> -->
                        </block>
                    </view>
                </view>
				
				<view class="mt20" v-else>
					<tui-no-data :fixed="false" imgUrl="https://cwmall.oss-cn-shanghai.aliyuncs.com/mp-icon/img_noorder_3x.png">暂无商品推荐</tui-no-data>
				</view>
            </view>

            <!--加载loadding-->
            <tui-loadmore v-if="loadding" :index="3" type="red"></tui-loadmore>
            <!-- <tui-nomore v-if="!pullUpOn"></tui-nomore> -->
            <!--加载loadding-->
            <view class="tui-safearea-bottom"></view>
			
			<!-- 联系客服 -->
			<tui-customer></tui-customer>

			<!-- 绑定成为客户/下级代理 -->
			<tui-modal :show="modal.showBindModal" custom>
				<bind-proxy-pane
					@onLogin='doBind'
					:type="modal.type"
					:nickName="modal.data.nickName"
					:avatarUrl="modal.data.avatarUrl">
				</bind-proxy-pane>
			</tui-modal>
			
			<custom-tab-bar name='home'></custom-tab-bar>
        </view>
    </view>
</template>
<script>
import { PRODUCTS_LIST } from "../../mixin/PRODUCTS_LIST"
import { PRODUCTS_DETAIL } from "../../mixin/PRODUCTS_DETAIL"
import CustomTabBar from "@/components/common/custom-tabbar/custom-tabbar.vue"
import BindProxyPane from '@/components/views/t-proxy-bind/t-proxy-bind.vue'
import { mapState } from 'vuex'
import constants from '@/constants'
import config from '@/config'

export default {
	components: { CustomTabBar, BindProxyPane },
	data() {
		return {
			hotSearch: [],
			banner: [{
				bannerPic:'https://cwmall.oss-cn-shanghai.aliyuncs.com/images/2020/06/24/15929908387259307.jpg'
			},{
				bannerPic:'https://cwmall.oss-cn-shanghai.aliyuncs.com/images/2020/06/24/15929908387259307.jpg'
			}],
			category: [],
			pageIndex: 1,
			loadding: false,
            pullUpOn: true,
            skeletonShow: true,
			modal: {
				showBindModal: false,
				type: '',
				data: {}
			}
		};
    },
    mixins: [PRODUCTS_LIST, PRODUCTS_DETAIL],
	computed: {
		statusBar() {
			const { systemInfo: { statusBarHeight } } = this.$store.state
			const menu = uni.getMenuButtonBoundingClientRect()
			return {
				top: statusBarHeight + (menu.top - statusBarHeight),
				height: menu.height + (menu.top - statusBarHeight),
				menuWidth: menu.width + uni.upx2px(14)
			}
		},
		...mapState(['USER', 'mallOwner'])
	},
    onLoad(opt){
		this.datas = {
			opt
		}
        this.$nextTick(()=>{
            this.init()
        })
    },
	methods: {
        async init(){
			this.GetBannerList()
            await this.getCategoryList()
            await this.GetProductListByHome((data)=>{
				setTimeout(()=>{
                    this.skeletonShow = false
                    this.PRODUCTS_LIST = []
                    this.PRODUCTS_LIST = data
					this.checkScene(this.datas.opt)
				},500)
			})
        },
        handleBannerClick({ productCode, productId }){
            productCode = productCode ? productCode : productId
            if(!productCode){
                return
            }
			uni.navigateTo({
				url: `/pagesB/productDetail/productDetail?productCode=${productCode}`
			})
        },
        // 获取商家分类列表
        async getCategoryList(){
            const response = await this.$api.GetCateList()
            let { data, total } = response
			// 类目分组 10个一组
			const cates = []
			let temp = []
			data.forEach(item => {
				if (temp.length < 10) {
					temp.push(item)
				} else {
					cates.push(temp)
					temp = [item]
				}
			})
			temp.length && cates.push(temp)
            this.category = cates
        },
        // 获取商家配置的banner没有的话需要一个兜底
        async GetBannerList(){
            const { data } = await this.$api.GetBannerList()
			if( Array.isArray(data) && data.length>0 ){
				this.banner = data
			}
        },
		tabbarSwitch: function(e) {
			let index = e.currentTarget.dataset.index;
			this.current = index;
			if (index != 0) {
				if (index == 1) {
					uni.navigateTo({
						url: '../shopcart/shopcart'
					});
				}else {
					uni.navigateTo({
						url: '../my/my'
					});
				}
			}
		},
		detail: function() {
			uni.navigateTo({
				url: '/pagesB/productDetail/productDetail'
			});
		},
		coupon() {
			uni.navigateTo({
				url: '/pagesB/coupon/coupon'
			});
		},
		classify: function() {
			uni.navigateTo({
				url: '../classify/classify'
			});
		},
		more: function(e) {
			let key = e.currentTarget.dataset.key || '';
			uni.navigateTo({
				url: '/pagesB/productList/productList?searchKey=' + key
			});
        },
		search: function() {
			uni.navigateTo({
				url: '/pagesB/search/search'
			});
		},
		/**
		 * 从分享卡片, 或扫码进入小程序的. 
		 * 判断是否有指定参数.
		 */
		async checkScene(opt) {
			const { scene } = opt
			if (scene) {
				const [type, customerId] = scene.split('_')
				this.modal.type = type
				const { success, data } = await this.$api.getCustomerInfo(customerId)

				if (type === 'r') {
					this.modal.showBindModal = true
				} else if (data) {
					this.modal.data = data
					if (type === 'c') {
						// 没有绑定过
						if (this.USER.isHasAgentor !== '1') {
							this.modal.showBindModal = true
						}
					} else if (type === 'd') {
						// 不是代理 并且 没有绑定过
						if (this.USER.role !== 2 && this.USER.isHasAgentor !== '1') {
							this.modal.showBindModal = true
						}
					}
					this.$store.dispatch('UPDATE_MALL_OWNER', this.modal.data)
				} else {
					uni.showModal({
						title: '操作提示',
						content: '没有找到指引您前来的分享者信息',
						showCancel: false,
					})
				}
			}
		},
		async doBind(type, userInfo) {
			if (type === 'c') {
				// 判断是否登录
				const { success, errMessage } = await this.$api.bindAgentor(this.modal.data.customerId)
				uni.showModal({
					title: '操作提示',
					content: success ? '登录成功' : errMessage,
					showCancel: false
				})
			} else if (['d', 'r'].includes(type)) {
				// 判断角色
				const { success, errMessage } = await this.$api.registerAgentor(type === 'd' ? this.modal.data.customerId : '#')
				uni.showModal({
					title: '操作提示',
					content: success ? '绑定成功' : errMessage,
					showCancel: false
				})
				if (success) {
					this.$store.dispatch('UPDATE_USER_ROLE', 2)
					uni.setStorageSync(constants.USERINFOBYWEIXIN, userInfo)
				}
			}
			
			if (type !== 'r') {
				this.$store.dispatch('UPDATE_MALL_OWNER', this.modal.data)
				// this.mallOwner = this.modal.data
			}
			this.modal.showBindModal = false
		}
    },
	onPullDownRefresh: function() {
		// let loadData = JSON.parse(JSON.stringify(this.productList));
		// loadData = loadData.splice(0, 10);
		// this.productList = loadData;
		// this.pageIndex = 1;
		// this.pullUpOn = true;
		// this.loadding = false;
		setTimeout(()=>{
			uni.stopPullDownRefresh();
		},300)
	},
	onReachBottom: function() {
		// if (!this.pullUpOn) return;
		// this.loadding = true;
		// if (this.pageIndex == 4) {
		// 	this.loadding = false;
		// 	this.pullUpOn = false;
		// } else {
		// 	let loadData = JSON.parse(JSON.stringify(this.productList));
		// 	loadData = loadData.splice(0, 10);
		// 	if (this.pageIndex == 1) {
		// 		loadData = loadData.reverse();
		// 	}
		// 	this.productList = this.productList.concat(loadData);
		// 	this.pageIndex = this.pageIndex + 1;
		// 	this.loadding = false;
		// }
	}
};
</script>

<style lang="scss">
page {
	background-color: #f7f7f7;
}

.container {
	padding-bottom: 100rpx;
	color: #333;
}

/*tabbar*/

.tui-tabbar {
	width: 100%;
	position: fixed;
	display: flex;
	align-items: center;
	justify-content: space-between;
	z-index: 99999;
	background: #fff;
	height: 100rpx;
	left: 0;
	bottom: 0;
	padding-bottom: env(safe-area-inset-bottom);
}

.tui-safearea-bottom {
	width: 100%;
	height: env(safe-area-inset-bottom);
}

.tui-tabbar::before {
	content: '';
	width: 100%;
	border-top: 1rpx solid #d9d9d9;
	position: absolute;
	top: 0;
	left: 0;
	-webkit-transform: scaleY(0.5);
	transform: scaleY(0.5);
}

.tui-tabbar-item {
	flex: 1;
	width: 25%;
	display: flex;
	align-items: center;
	flex-direction: column;
	justify-content: space-between;
	font-size: 24rpx;
	color: #666;
	height: 80rpx;
}

.tui-ptop-4 {
	padding-top: 4rpx;
}

.tui-scale {
	font-weight: bold;
	transform: scale(0.8);
	transform-origin: center 100%;
	line-height: 30rpx;
}

.tui-item-active {
	color: #e41f19 !important;
}

/*tabbar*/

.tui-header {
	width: 100%;
	box-sizing: border-box;
	background-color: #e41f19;
	display: flex;
	flex-direction: column;
	position: fixed;
	left: 0;
	top: 0;
	/* #ifdef H5 */
	top: 44px;
	/* #endif */
	z-index: 999;
	padding-bottom: 10px;
	
	.tui-placeholder {
		width: 100%;
	}
	.tui-header-container {
		padding: 0 30rpx 0 20rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
}

.tui-rolling-search {
	width: 100%;
	height: 60rpx;
	border-radius: 35rpx;
	padding: 0 40rpx 0 30rpx;
	box-sizing: border-box;
	background-color: #fff;
	display: flex;
	align-items: center;
	flex-wrap: nowrap;
	color: #999;
}

.tui-category {
	font-size: 24rpx;
	color: #fff;
	display: flex;
	align-items: center;
	justify-content: center;
	flex-direction: column;
	margin: 0;
	margin-right: 22rpx;
	flex-shrink: 0;
}

.tui-category-scale {
	transform: scale(0.7);
	line-height: 24rpx;
}

.tui-icon-category {
	line-height: 20px !important;
	margin-bottom: 0 !important;
}

.tui-swiper {
	font-size: 26rpx;
	height: 60rpx;
	flex: 1;
	padding-left: 12rpx;
}

.tui-swiper-item {
	display: flex;
	align-items: center;
}

.tui-hot-item {
	line-height: 26rpx;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.tui-header-banner {
	// padding-top: 100rpx;
	box-sizing: border-box;
	background: #e41f19;
}

.tui-hot-search {
	color: #fff;
	font-size: 24rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 20rpx;
	box-sizing: border-box;
	position: relative;
	z-index: 2;
}

.tui-hot-tag {
	background-color: rgba(255, 255, 255, 0.15);
	padding: 10rpx 24rpx;
	border-radius: 30rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	line-height: 24rpx;
}

.tui-banner-bg {
	display: flex;
	height: 180rpx;
	background-color: #e41f19;
	position: relative;
}

.tui-primary-bg {
	width: 50%;
	display: inline-block;
	height: 224rpx;
	border: 1px solid transparent;
	position: relative;
	z-index: 1;
	background-color: #e41f19;
}

.tui-route-left {
	transform: skewY(8deg);
}

.tui-route-right {
	transform: skewY(-8deg);
}

.tui-banner-box {
	width: 100%;
	padding: 0 20rpx;
	box-sizing: border-box;
	position: absolute;
	/* overflow: hidden; */
	z-index: 99;
	bottom: -80rpx;
	left: 0;
	.mall-owner {
		font-size: 26rpx;
		color: #fff;
		padding: 0 0 10rpx;
		display: inline-block;
		.owner-wrapper {
			display: flex;
			justify-content: center;
			align-items: center;
			.owner-avatar {
				width: 60rpx;
				height: 60rpx;
				margin-right: 20rpx;
				.owner-avatar-img {
					width: 60rpx;
					height: 60rpx;
					border-radius: 30rpx;
				}
			}
		}
	}
}

.tui-banner-swiper {
	width: 100%;
	height: 240rpx;
	border-radius: 12rpx;
	overflow: hidden;
	transform: translateY(0);
}

.tui-slide-image {
	width: 100%;
	height: 240rpx;
	display: block;
}

/* #ifdef MP-WEIXIN */
.tui-banner-swiper .wx-swiper-dot {
	width: 8rpx;
	height: 8rpx;
	display: inline-flex;
	background: none;
	justify-content: space-between;
}

.tui-banner-swiper .wx-swiper-dot::before {
	content: '';
	flex-grow: 1;
	background-color: rgba(255, 255, 255, 0.8);
	border-radius: 16rpx;
	overflow: hidden;
}

.tui-banner-swiper .wx-swiper-dot-active::before {
	background-color: #fff;
}

.tui-banner-swiper .wx-swiper-dot.wx-swiper-dot-active {
	width: 16rpx;
}

/* #endif */

/* #ifndef MP-WEIXIN */
>>> .tui-banner-swiper .uni-swiper-dot {
	width: 8rpx;
	height: 8rpx;
	display: inline-flex;
	background-color: none;
	justify-content: space-between;
}

>>> .tui-banner-swiper .uni-swiper-dot::before {
	content: '';
	flex-grow: 1;
	background-color: rgba(255, 255, 255, 0.8);
	border-radius: 16rpx;
	overflow: hidden;
}

>>> .tui-banner-swiper .uni-swiper-dot-active::before {
	background-color: #fff;
}

>>> .tui-banner-swiper .uni-swiper-dot.uni-swiper-dot-active {
	width: 16rpx;
}

/* #endif */

.tui-product-category {
	background-color: #fff;
	padding: 80rpx 20rpx 10rpx 20rpx;
	box-sizing: border-box;
	font-size: 24rpx;
	color: #555;
	// margin-bottom: 20rpx;
	.tui-catetory-swiper {
		width: 100%;
		height: 330rpx;
		transform: translateY(0);
		.tui-catetory-group {
			display: flex;
			align-items: center;
			justify-content: flex-start;
			flex-wrap: wrap;
		}
	}
}

.tui-category-item {
	width: 20%;
	// height: 118rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	flex-direction: column;
	padding-top: 30rpx;
}

.tui-category-img {
	height: 80rpx;
	width: 80rpx;
	display: block;
}

.tui-category-name {
	line-height: 24rpx;
	margin-top: 10rpx;
	text-overflow: ellipsis;
	overflow: hidden;
	white-space: nowrap;
	max-width: 90%;
}

.tui-product-box {
	margin-top: 20rpx;
	padding: 0 20rpx;
	box-sizing: border-box;
}

.tui-pb-20 {
	padding-bottom: 20rpx;
}

.tui-bg-white {
	background-color: #fff;
}

.tui-group-name {
	width: 100%;
	font-size: 32rpx;
	font-weight: bold;
	text-align: center;
	padding: 24rpx 0;
	display: flex;
	align-items: center;
	justify-content: center;
}

.tui-activity-box {
	display: flex;
	border-radius: 12rpx;
	overflow: hidden;
}

.tui-activity-img {
	width: 50%;
	display: block;
}

.tui-new-box {
	display: flex;
	align-items: center;
	justify-content: space-between;
	flex-wrap: wrap;
}

.tui-new-item {
	width: 49%;
	height: 200rpx;
	padding: 0 20rpx;
	box-sizing: border-box;
	display: flex;
	align-items: center;
	background: #f5f2f9;
	position: relative;
	border-radius: 12rpx;
}

.tui-new-mtop {
	margin-top: 2%;
}

.tui-title-box {
	font-size: 24rpx;
}

.tui-new-title {
	line-height: 32rpx;
	word-break: break-all;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
}

.tui-new-price {
	padding-top: 18rpx;
}

.tui-new-present {
	color: #ff201f;
	font-weight: bold;
}

.tui-new-original {
	display: inline-block;
	color: #a0a0a0;
	text-decoration: line-through;
	padding-left: 12rpx;
	transform: scale(0.8);
	transform-origin: center center;
}

.tui-new-img {
	width: 160rpx;
	height: 160rpx;
	display: block;
	flex-shrink: 0;
}

.tui-new-label {
	width: 56rpx;
	height: 56rpx;
	border-top-left-radius: 12rpx;
	position: absolute;
	left: 0;
	top: 0;
}

.tui-product-list {
	display: flex;
	justify-content: space-between;
	flex-direction: row;
	flex-wrap: wrap;
	box-sizing: border-box;
	/* padding-top: 20rpx; */
}

.tui-product-container {
	flex: 1;
	margin-right: 2%;
}

.tui-product-container:last-child {
	margin-right: 0;
}

.tui-pro-item {
	width: 100%;
	margin-bottom: 4%;
	background: #fff;
	box-sizing: border-box;
	border-radius: 12rpx;
	overflow: hidden;
}

.tui-pro-img {
	width: 100%;
	display: block;
}

.tui-pro-content {
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	box-sizing: border-box;
	padding: 20rpx;
}

.tui-pro-tit {
	color: #2e2e2e;
	font-size: 26rpx;
	word-break: break-all;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
}

.tui-pro-price {
	padding-top: 18rpx;
}

.tui-sale-price {
	font-size: 34rpx;
	font-weight: 500;
	color: #e41f19;
}

.tui-factory-price {
	font-size: 24rpx;
	color: #a0a0a0;
	text-decoration: line-through;
	padding-left: 12rpx;
}

.tui-pro-pay {
	padding-top: 10rpx;
	font-size: 24rpx;
	color: #656565;
}

</style>
